package top.codedance.iotp.tools.terminal.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.tools.terminal.TerminalApplication;
import top.codedance.iotp.tools.terminal.bean.ComConnectParam;
import top.codedance.iotp.tools.terminal.comer.CallOwner;
import top.codedance.iotp.tools.terminal.comer.ComClient;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.net.URL;

/**
 * @author xuedianfu
 */
public class ModbusAutoChecker extends javax.swing.JDialog implements CallOwner {
    private AddModbus modbus;
    private WaitLoading waitLoading = new WaitLoading(this);
    private String[] colums = new String[]{"从机号", "在线状态"};
    private String[][] tableData = new String[][]{};
    private DefaultTableModel tm;

    /**
     * Creates new form ModbusAutoChecker
     */
    public ModbusAutoChecker(AddModbus modbus) {
        super(modbus, true);
        this.modbus = modbus;
        initComponents();

        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(this.modbus.getClientPluginTester().getShellFrame());
        setMinimumSize(new Dimension(600, 500));
        setResizable(true);
        setTitle("代码飞舞采控系统-ModBus设备自检器");

        initResultTable();
    }

    public void setClientId(String id) {
        jtf_client.setText(id);
    }

    private void initResultTable() {
        tm = new DefaultTableModel(tableData, colums);
        jt_result.setModel(tm);
        jt_result.getTableHeader().setReorderingAllowed(false);
    }

    @Override
    public String getOwnerClassName() {
        return this.getClass().getTypeName();
    }

    @Override
    public void appendResult(String data) {
        over();
        TerminalApplication.syslogInfo(data);
        if (data != null) {
            try {
                initResultTable();
                JSONArray result = JSON.parseArray(data);
                JSONObject jo;
                for (int i = 0; i < result.size(); i++) {
                    jo = result.getJSONObject(i);
                    tm.addRow(new String[]{jo.getString("slaveId"), jo.getBoolean("onLine") ? "在线" : "离线"});
                }
            } catch (Exception e) {
                TerminalApplication.syslogInfo(e.getMessage());
            }
        }
    }

    @Override
    public void appendError(String data) {
        over();
        if (data != null) {
            TerminalApplication.syslogInfo(data);
            JSONObject jsonObject = JSON.parseObject(data);
            JOptionPane.showMessageDialog(this.getRootPane(), "执行失败: " + jsonObject.getString("msg"));
        }
    }

    private void createComClient(String comName, String btl, String sjw, String tzw, String xyw) {
        this.modbus.cpt.sf.ccs.put(comName, new ComClient(this, new ComConnectParam(comName, Integer.parseInt(btl), Integer.parseInt(sjw), Integer.parseInt(tzw), Integer.parseInt(xyw))));
    }

    private void comSendCmd(String cmd) {
        if (this.modbus.cpt.currentConnectionParam == null || this.modbus.cpt.currentConnectionParam.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "请选取连接配置。");
            return;
        }
        if (!this.modbus.cpt.currentConnectionParam.containsKey("com") || this.modbus.cpt.currentConnectionParam.getString("com").isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "请选取Com口的连接配置。");
            return;
        }
        waiting();
        TerminalApplication.pool.submit(() -> {
            JSONObject com = this.modbus.cpt.currentConnectionParam.getJSONObject("com");
            String comName = com.getString("value");
            String btl = this.modbus.cpt.currentConnectionParam.getString("btl");
            String sjw = this.modbus.cpt.currentConnectionParam.getString("sjw");
            String tzw = this.modbus.cpt.currentConnectionParam.getString("tzw");
            String xyw = this.modbus.cpt.currentConnectionParam.getString("xyw");
            if (!this.modbus.cpt.sf.ccs.containsKey(comName)) {
                createComClient(comName, btl, sjw, tzw, xyw);
            } else {
                ComClient comClient = this.modbus.cpt.sf.ccs.get(comName);
                comClient.setOwner(this);
            }
            JSONObject command = new JSONObject();
            command.put("cmd", cmd);
            ComClient comClient = this.modbus.cpt.sf.ccs.get(comName);
            comClient.send(command.toJSONString());
        });
    }

    private void waiting() {
        waitLoading.open();
    }

    private void over() {
        if (waitLoading != null) {
            waitLoading.close();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtf_client = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jtf_devices = new javax.swing.JTextField();
        jb_run = new javax.swing.JButton();
        jb_clean = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jt_result = new javax.swing.JTable();

        jLabel1.setText("Client id：");

        jtf_client.setText("0");
        jtf_client.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtf_clientKeyTyped(evt);
            }
        });

        jLabel2.setText("设备数：");

        jtf_devices.setText("32");
        jtf_devices.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtf_devicesKeyTyped(evt);
            }
        });

        jb_run.setText("执行");
        jb_run.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_runActionPerformed(evt);
            }
        });

        jb_clean.setText("清空");
        jb_clean.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_cleanActionPerformed(evt);
            }
        });

        jt_result.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jt_result);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 763, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jtf_client, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jtf_devices, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jb_run)
                        .addGap(18, 18, 18)
                        .addComponent(jb_clean)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtf_client, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jtf_devices, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jb_run)
                    .addComponent(jb_clean))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jb_runActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_runActionPerformed
        if (jtf_client.getText().isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Client ID 不能为空, 必须为无符号整数，且在客户端配置中存在。");
            return;
        }
        JSONObject commandParams = new JSONObject();
        commandParams.put("plugin", Command.MODBUS_COMMAND);
        JSONObject clientJo = new JSONObject();
        clientJo.put("id", Integer.valueOf(jtf_client.getText()));
        JSONObject data = new JSONObject();
        data.put("devices", Integer.valueOf(jtf_devices.getText()));
        clientJo.put("data", data);
        commandParams.put("client", clientJo);
        commandParams.put("runner", this.modbus.cpt.RUNNER_TYPE);
        comSendCmd(commandParams.toJSONString());
    }//GEN-LAST:event_jb_runActionPerformed

    private void jb_cleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_cleanActionPerformed
        initResultTable();
    }//GEN-LAST:event_jb_cleanActionPerformed

    private void jtf_clientKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtf_clientKeyTyped
        JTextField jtf = (JTextField)evt.getSource();
        if (!TerminalApplication.numbers.contains(evt.getKeyChar())) {
            evt.consume();
        }
        try{
            Integer.parseInt(jtf.getText());
            if(jtf.getText().startsWith("0")){
                jtf.setText(jtf.getText().replaceAll("^0+", ""));
            }
        }catch (Exception e){
            jtf.setText("0");
        }
    }//GEN-LAST:event_jtf_clientKeyTyped

    private void jtf_devicesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtf_devicesKeyTyped
        jtf_clientKeyTyped(evt);
    }//GEN-LAST:event_jtf_devicesKeyTyped

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jb_clean;
    private javax.swing.JButton jb_run;
    private javax.swing.JTable jt_result;
    private javax.swing.JTextField jtf_client;
    private javax.swing.JTextField jtf_devices;
    // End of variables declaration//GEN-END:variables
}
